/*
 * BlockManager.h
 *
 *  Created on: Mar 22, 2010
 *      Author: Lukasz Spintzyk
 */

#ifndef BLOCKREADER_H_
#define BLOCKREADER_H_

#ifndef PH_H_
#include "ph.h"
#endif

class SuperBlock;
class IOStream;
class BlockDesc;

class BlockManager
{
public:
	typedef  std::map<uint32_t, BlockDesc*> BlockMap;
	typedef BlockMap::const_iterator BlockMap_cit;
	typedef BlockMap::iterator BlockMap_it;

    BlockManager(IOStream& io, SuperBlock& sb);
    ~BlockManager();

    void readSuperBlock();
    void writeSuperBlock();

    void writeStringToBlock(uint32_t block_number, const char* string);

    void getBlock(uint32_t nr, void* buffer);
    void setBlock(uint32_t nr, const void* buffer);

    void getBlock(uint32_t gr, uint32_t nr, void* buffer);
    void setBlock(uint32_t gr, uint32_t nr, const void* buffer);

    BlockDesc& getBlockGroupDesc(uint32_t nb);
    void setBlockGroupDesc(BlockDesc& group);

    uint32_t getFileSize();

    uint32_t reserveBlocksNearTo(
							uint32_t block,
							uint32_t num,
							std::vector< std::pair< uint32_t, uint32_t > >& reserved);

    uint32_t reserveFreeInode();

    uint32_t tryReserveBlocksNearTo(uint32_t block,const uint32_t num);

    void updateFreeBlocks(int32_t add);
    void freeBlock(uint32_t blockNumber);

private:
    IOStream& d_io;
    SuperBlock& d_sb;

    byte* d_buffer;

    BlockMap d_groups;

};

#endif /* BLOCKREADER_H_ */
